package com.jinghang.nginxProject.utils

import java.util.regex.Pattern

object StringUtil {

  /**
    * 获取字符串第n个分隔符所在的位置
    * 例如 获取"   sffb"fdfdg"vdfd"fdfd   " 第2个"的位置为4
    *
    * @param str      输入的字符串
    * @param operator 分隔符号
    * @param num      第几个分隔符
    * @return
    */
  def getCharPosition(str: String, operator: String, num: Int) = {
    val matcher = Pattern.compile(operator).matcher(str)
    var count = 1
    /*
      matcher.find
      1.如果能匹配上"就返回true
      2.每调用一次matcher.find，就匹配下一个"
     */
    var flage = matcher.find
    while (flage) {
      if (count == num) {
        flage = false
      } else {
        matcher.find
        count += 1
      }
    }
    matcher.start
  }

  def getUserAgent(nginx_log:String):String={
    val index_start = getCharPosition(nginx_log, "\"", 7)
    val index_end = getCharPosition(nginx_log, "\"", 8)
    nginx_log.substring(index_start+1,index_end)
  }


  def main(args: Array[String]): Unit = {
    val str = "10.100.0.1 - - [10/Nov/2016:00:01:02 +0800] \"HEAD / HTTP/1.1\" 301 0 \"117.121.101.40\" \"-\" - \"curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.16.2.3 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2\" \"-\" - - - 0.000"
//    val index = StringUtil.getCharPosition(str, "\"", 7)
//    println(index)
//    val index2 = StringUtil.getCharPosition(str, "\"", 8)
//    println(index2)
//
//    val userAgent = str.substring(index+1,index2)
//    println(userAgent)

    val str1 = getUserAgent(str)
    println(str1)


  }

}
